<?php

	/**
    * @framework : My Framework
    *
    * @author: fatangel26@gmail.com - Nguyễn Bảo Trung.
    *
    * @class : cart_controller
    */


	class cart_controller extends my_controller
	{
	    var $_cart_contents = array();

		public function __construct()
        {
            parent::__construct();

            /*LOAD AUTOMATIC HELPER & MODEL*/
            $this->_helper->session = new helper_session();
            $this->_helper->text    = new helper_text;

            $this->_model->product  = new model_product();
            $this->_model->cart     = new model_cart();

            /*ASSIGN $_SESSION TO VARAIBLE*/
            if($this->_helper->session->get_userdata('jewel_cart_contents') !== FALSE)
                $this->_cart_contents = $this->_helper->session->get_userdata('jewel_cart_contents');
            else
            {
                /*SET DEFAULT IF NO ISSET $_SESSION*/
                $this->_cart_contents['total_items'] = 0;
                $this->_cart_contents['cart_total'] = 0;
            }
        }

        public function addcart()
        {
            /*echo $_POST['product_id']."-".$_POST['quantity'];*/

            (int)   $product_id = $_POST['product_id'];
            (array) $product    = $this->_model->product->getProductById(array('product_id' => $product_id));

            /*
            echo "<pre>";
            print_r($product);
            */

            /*CHECK PRODUCT EXISTS AND QUANTITY*/
            if(!$product)
            {
                $json['error'] = 1;
            }
            else
            {
                if($product['product_quantity'] == 0 || $product['product_quantity'] < $_POST['quantity'])
                {
                    $json['error'] = 2;
                }
                else
                {

                    (int) $quantity = $_POST['quantity'];

                    /*NEED TO ADD QUANTITY*/
                    if(!empty($this->_cart_contents))
                    {
                        foreach($this->_cart_contents as $val):
                            if($val['id'] == $product_id)
                            {
                                $quantity = $val['quantity'] + $quantity;
                                break;
                            }
                        endforeach;
                    }

                    $cartInsert = array(
                        'id'            => $product_id,
                        'quantity'      => $quantity,
                        'product_name'  => $product['product_name']
                    );

                    /*SALE-OFF PRICE OR NO ...*/
                    if($product['product_price_sale'] != 0)
                    {
                        $cartInsert['price'] = $product['product_price_sale'];
                    }
                    else
                    {
                        $cartInsert['price'] = $product['product_price'];
                    }

                    /*NEED FOR SECOND ADD PRODUCT WITH SAME PRODUCT_ID*/
                    if(isset($this->_cart_contents[$product_id]))
                        unset($this->_cart_contents[$product_id]);

                    foreach($cartInsert as $key => $val):

                        $this->_cart_contents[$product_id][$key] = $val;

                    endforeach;

                    /*
                    echo "<pre>";
                    print_r($this->_cart_contents);
                    */
                    $this->save_cart();

                    /*ASSIGN ALL INFORMATION OF PRODUCT TO STRING JSON*/
                    if(!empty($this->_cart_contents))
                    {
                        foreach($this->_cart_contents as $val):

                            if($val['id'] == $product_id)
                            {
                                $json = array(
                                    'img'               => $product['product_thumb'],
                                    'product_name'      => $val['product_name'],
                                    'product_quantity'  => $val['quantity'],
                                    'product_price'     => number_format($val['price'],0,",","."),
                                    'menu_slug'         => $product['menu_slug'],
                                    'slug'              => $product['slug']
                                );

                                break;
                            }

                        endforeach;

                        $json['product_total_quantity'] = $this->_cart_contents['total_items'];
                        $json['product_total_price']    = number_format($this->_cart_contents['cart_total'],0,",",".");
                    }

                }//End else

                /*GET RANDOM PRODUCTS TO SHOW IN VIEW*/

                if($this->getRandomProduct($product_id))
                {
                    (int) $count = 0;

                    foreach($this->getRandomProduct($product_id) as $randoms):

                        $json['random'][$count]['random_product_name']  = $this->_helper->text->limited_character(ucfirst($randoms['product_name']),21);
                        $json['random'][$count]['random_product_price'] = number_format($randoms['product_price'],0,",",".");
                        $json['random'][$count]['random_product_img']   = $randoms['product_thumb'];
                        $json['random'][$count]['random_menu_slug']     = $randoms['menu_slug'];
                        $json['random'][$count]['random_slug']          = $randoms['slug'];
                        $json['random'][$count]['random_product_id']    = $randoms['product_id'];

                        $count++;

                    endforeach;
                }

            }

            echo json_encode($json);

        }//End function addcart()

        private function getRandomProduct($product_id)
        {
            (array) $random_products = $this->_model->product->getRandomProduct($product_id);

            return $random_products;
        }//End fucntion getRandomProduct()

        public function destroycart()
        {
            $this->_helper->session->unset_userdata('jewel_cart_contents');
            $this->redirect("index.php?module=cart&action=viewcart");
        }//End function destroycart()

        public function viewcart()
        {
            $this->_data['title']     = 'Jewel | Giỏ hàng';
            $this->_data['head_name'] = 'Giỏ hàng';

            /*
            echo "<pre>";
            print_r($this->_helper->session->get_userdata('jewel_cart_contents'));
            echo "</pre>";
            */
            //$data['cart_contents'] = $this->_helper->session->get_userdata('jewel_cart_contents');

            $this->_data['content'] = $this->view("cart/viewcart", $data = '' , TRUE);
            $this->view("layout",$this->_data);
        }//End function viewcart()

        public function delcart()
        {
            foreach ($this->_cart_contents as $key => $val)
            {
                if($key === 'cart_total' || $key === 'total_items')
                    continue;
                if($key == $_POST['id'])
                {
                    unset($this->_cart_contents[$key]);
                    break;
                }
            }

            $this->_helper->session->unset_userdata('jewel_cart_contents');
            /*$this->_helper->session->set_userdata('jewel_cart_contents',$this->_cart_contents);*/
            $this->save_cart();

            if($this->_cart_contents['total_items'] > 0)
            {
                $json['total_items'] = $this->_cart_contents['total_items'];
                $json['view']        = $this->view('cart/viewcart', $data = '', TRUE);
            }
            else
                $json['view'] = 1;

            echo json_encode($json);
        }//End function delcart()

        public function updatecart()
        {
            (array) $product_quantity = $_POST['product_quantity'];

            /*
            echo "<pre>";
            print_r($product_quantity);
            */

            foreach($this->_cart_contents as $key => $val)
            {

                if($key === 'total_items' || $key === 'cart_total')
                    continue;

                foreach($product_quantity as $id => $qty):

                    if($key == $id)
                    {
                        if($qty == 0 || $qty === '' || $qty < 0):
                            unset($this->_cart_contents[$key]);
                        else:
                            $this->_cart_contents[$key]['quantity'] = $qty;
                        endif;

                        break;
                    }

                endforeach;
            }

            $this->_helper->session->unset_userdata('jewel_cart_contents');
            $this->save_cart();

            $this->redirect("index.php?module=cart&action=viewcart");
            /*
            echo "<pre>";
            print_r($this->_cart_contents);
            echo "</pre>";
            */

        }

        public function checkout()
        {
            $this->_data['title']     = 'Jewel | Đặt hàng';
            $this->_data['head_name'] = 'Đặt hàng';

            /*MAKE CAPTCHA*/
            $this->_helper->captcha = new helper_captcha();

            $data['captcha'] = $this->_helper->captcha->make_captcha();

            $this->_data['content']   = $this->view("cart/checkout", $data, TRUE);
            $this->view("layout", $this->_data);
        }

        public function contact()
        {
            extract($_POST);

            $this->_helper->validation = new helper_validation();

            /*CHECK REQUIRED*/
            if($this->_helper->validation->required($customer_name) === FALSE)
                $json['error']['customer_name'] = "<span class='error'>Họ và tên không được để trống</span>";

            if($this->_helper->validation->required($customer_phone) === FALSE)
                $json['error']['customer_phone'] = "<span class='error'>Số điện thoại không được để trống</span>";

            if($this->_helper->validation->required($customer_email) === FALSE)
                $json['error']['customer_email'] = "<span class='error'>Email không được để trống</span>";

            if($this->_helper->validation->required($captcha) === FALSE)
                $json['error']['captcha'] = "<span class='error'>Captcha không được để trống</span>";

            if($this->_helper->validation->required($customer_address) === FALSE)
                $json['error']['customer_address'] = "<span class='error'>Địa chỉ không được để trống</span>";

            /*CHECK EMAIL*/
            if($this->_helper->validation->valid_email($customer_email) === FALSE)
                $json['error']['customer_email'] = "<span class='error'>Email không đúng định dạng</span>";

            /*CHECK PHONE*/
            if($this->_helper->validation->is_numeric($customer_phone) === FALSE)
                $json['error']['customer_phone'] = "<span class='error'>Số điện thoại không đúng định dạng</span>";

            if($this->_helper->validation->check())
            {
                if($txt_cap !== $captcha)
                {
                    $json['error']['captcha']  = '<span class="error">Captcha không chính xác</span>';
                }
                else
                {
                    $strInsert = array(
                        'customer_name'     => $customer_name,
                        'customer_email'    => $customer_email,
                        'customer_phone'    => $customer_phone,
                        'customer_address'  => $customer_address
                    );

                    $check = $this->_model->cart->create($strInsert);

                    if(!$check)
                    {
                        $json['error']['error_msg'] = 'Có lỗi trong quá trình tạo hoá đơn. Mong bạn thông cảm.';
                    }
                    else
                    {
                        /*SAVE DATABASE SUCCESS -> SEND EMAIL FOR CUSTOMER*/
                        $json['success'] = 1;

                        $this->_helper->email = new helper_phpmailer();

                        $data = array(
                            'customer_name'     => $customer_name,
                            'customer_email'    => $customer_email,
                            'customer_phone'    => $customer_phone,
                            'customer_address'  => $customer_address
                        );

                        /*CONFIG EMAIL*/
                        $subject = 'Xác nhận mua hàng từ website Jewel.com.vn';
                        $body    = $this->view('email/template', $data, TRUE);

                        $this->_helper->email->send_email($customer_email, $subject, $body);

                        /*DESTROY CART*/
                        $this->_helper->session->unset_userdata('jewel_cart_contents');
                    }
                }
            }

            echo json_encode($json);
        }

        public function success()
        {
            if(!$this->_helper->session->get_userdata('jewel_cart_contents'))
            {
                $this->_data['title']     = 'Jewel | Đặt hàng';
                $this->_data['head_name'] = 'Đặt hàng';
                $this->_data['content']   = $this->view("cart/success", $data='', TRUE);

                $this->view("layout", $this->_data);
            }
            else
            {
                $this->redirect("index.php?module=cart&action=viewcart");
            }
        }

        private function save_cart()
        {
            /*NEED TO CACULATION AGAIN*/
            unset($this->_cart_contents['total_items']);
            unset($this->_cart_contents['cart_total']);

            /*CACULATION*/
            (int) $total_items = 0;
            (int) $cart_total  = 0;

            foreach($this->_cart_contents as $product_id => $val)
            {
                $cart_total  += ($val['price'] * $val['quantity']);
                $total_items += $val['quantity'];

                /*CACULATION SUBTOTAL*/
                $this->_cart_contents[$product_id]['subtotal'] = ($this->_cart_contents[$product_id]['price'] * $this->_cart_contents[$product_id]['quantity']);
            }

            $this->_cart_contents['total_items'] = $total_items;
            $this->_cart_contents['cart_total']  = $cart_total;

            $this->_helper->session->set_userdata('jewel_cart_contents', $this->_cart_contents);
            
            /*
            echo "<pre>";
            print_r($this->_helper->get_userdata('jewel_cart_contents'));
            */
        }//End function save_cart()
	}


    /* End of file cart_controller.php */
    /* Location: .//D/root/my_framework/controllers/cart_controller.php */


